<template>
  <div class="header-container">
    <nav-bar :title="'分类'"></nav-bar>
  </div>
  <div class="main-container">
    <van-tree-select
      :items="items"
      v-model:active-id="activeId"
      v-model:main-active-index="activeIndex"
      @click-nav="clickNav"
    >
      <template #content>
        <template v-if="selectedItem != null">
          <template v-for="child of selectedItem.children" :key="child.id">
            <van-cell>
              <template #title>
                <div style="border-left: 3px solid red; padding-left: 4px">
                  {{ child.name }}
                </div>
              </template>
            </van-cell>
            <van-grid :column-num="2" :border="false">
              <van-grid-item
                v-for="childChild of child.children"
                :key="childChild.id"
                icon="label-o"
                :text="childChild.name"
                @click="clickDetail(childChild)"
              />
            </van-grid>
          </template>
        </template>
      </template>
    </van-tree-select>
  </div>
  <div class="footer-container">
    <tab-bar activeItem="category" />
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  watch,
  watchEffect,
} from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import { useRoute, useRouter } from "vue-router";
import categoryService from "@/services/category.service";
import { AxiosError } from "axios";
import { Toast, TreeSelectChild, TreeSelectItem } from "vant";
import PmsCategory from "@/entity/PmsCategory";

type StateType = {
  categories: PmsCategory[];
  items: TreeSelectItem[];
  /**
   * 左侧数据数组下标
   */
  activeIndex: number | null;
  /**
   * 右侧数据数组下标
   */
  activeId: number | null;
  selectedItem?: PmsCategory | null;
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      categories: [],
      items: [],
      activeId: null,
      activeIndex: null,
      selectedItem: null,
    });

    onMounted(() => {
      load();
    });

    const load = async () => {
      try {
        const list = await categoryService.list();
        state.categories = [...list];

        state.items = [...buildItems(state.categories)];
        if (state.items && state.items.length > 0) {
          state.selectedItem = state.categories[0];
          state.activeId = 0;
          state.activeIndex = 0;
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const buildItems = (categories: PmsCategory[]): TreeSelectItem[] => {
      if (categories == null) {
        return [];
      }
      let items: TreeSelectItem[] = [];
      categories.forEach((c) => {
        let item: TreeSelectItem = {
          text: c.name || "",
        };
        item.children = buildChildItems(c.children || []);
        items.push(item);
      });
      return items;
    };

    const buildChildItems = (categories: PmsCategory[]): TreeSelectChild[] => {
      if (categories == null) {
        return [];
      }
      let items: TreeSelectChild[] = [];
      categories.forEach((c) => {
        let item: TreeSelectChild = {
          id: c.id,
          text: c.name || "",
        };
        items.push(item);
      });
      return items;
    };

    const clickNav = (idx: number) => {
      state.selectedItem = state.categories[idx];
    };

    const clickDetail = (category: PmsCategory) => {
      router.push({
        path: "/product",
        query: {
          categoryId: category.id,
          categoryName: category.name,
        },
      });
    };

    return {
      ...toRefs(state),
      clickNav,
      clickDetail,
    };
  },
});
</script>

<style scoped></style>
